using System;
using System.Collections;
using TMPro;
using UnityEngine;

public class ScoreManager : MonoBehaviour
{
    public TextMeshProUGUI scoreText;
    public float scoreAnimationDuration = 1f;
    public float scoreUpdateInterval = 0.05f;
    private int currentDisplayScore = 0;
    private int actualScore = 0;
    [SerializeField] private Board board;

    void Start()
    {
        UpdateScoreDisplay(0);
        if(board!=null)
        {
            board.onLinesCleared+=HandleLinesCleared;
        }
        else
        {
            Debug.Log("引用空Board");
        }
    }
    private void HandleLinesCleared(int lines)
    {
        int scroeToAdd = lines == 4?100:lines*10;
        //累加分数
        AddScore(scroeToAdd);
    }
    private void AddScore(int scroeToAdd)
    {
        actualScore+= scroeToAdd;
        Debug.Log($"得{actualScore}分");
        UpdateScoreDisplay(actualScore);
        StartCoroutine(AnimateScore());
    }
    private IEnumerator AnimateScore()
    {
        float animationtime = 0f;
        int startScore = currentDisplayScore;
        while(animationtime<scoreAnimationDuration)
        {
            animationtime += scoreUpdateInterval;
            float progress = animationtime/scoreAnimationDuration;
            currentDisplayScore = (int)Mathf.Lerp(startScore,actualScore,progress);
            UpdateScoreDisplay(currentDisplayScore);
            yield return new WaitForSeconds(scoreUpdateInterval);
        }
        currentDisplayScore = actualScore;
        UpdateScoreDisplay(currentDisplayScore);
    }
    private void UpdateScoreDisplay(int score)
    {
        scoreText.text = $"Score:{score}";
    }
    public void ResetScore()
    {
        actualScore = 0;
        currentDisplayScore = 0;
        UpdateScoreDisplay(0);
    }

}
